package com.xu.cloud.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * Builder工具类, 用于创建对象
 *
 * @author xuguan
 * @since 2025/4/2
 */
public class BuilderUtil<T> {
    private final Supplier<T> instantiate;
    private final List<Consumer<T>> consumers = new ArrayList<>();

    public BuilderUtil(Supplier<T> instantiate) {
        this.instantiate = instantiate;
    }

    public static <T> BuilderUtil<T> of(Supplier<T> instantiate) {
        return new BuilderUtil<>(instantiate);
    }

    public <V> BuilderUtil<T> with(BiConsumer<T, V> setter, V v) {
        consumers.add(o -> setter.accept(o, v));
        return this;
    }

    public T build() {
        T instance = instantiate.get();
        consumers.forEach(c -> c.accept(instance));
        return instance;
    }
}
